#include"mystdio.h"
#include<string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#include<stdlib.h>
//初始化MyFile
MyFile* BuyFile(int fd, int flag)
{
    MyFile* f = (MyFile*)malloc(sizeof(MyFile));
    if(f == NULL)
    {
        perror("malloc fail\n");
        return NULL;
    }
    f->bufferlen = 0;
    f->fileno = fd;
    f->flag = flag;
    memset(f->outbuffer, 0, sizeof(f->outbuffer));
    f->flush_method = LINE_FLUSH;
    return f;
}
MyFile* MyFopen(const char* path, const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode,"w") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag = O_CREAT | O_WRONLY | O_APPEND;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode,"r") == 0)
    {
        flag = O_RDWR;
        fd = open(path, flag);
    }
    else 
    {}
    if(fd < 0) 
    {
        perror("open fail\n");
        return NULL;
    }
    //打开文件之后需要申请MyFile
    return BuyFile(fd, flag); 
}

void MyFclose(MyFile* file)
{
    //关闭文件要进行刷新
    if(file->fileno < 0) return;
    MyFflush(file);
    close(file->fileno);
    free(file);
}
void MyFflush(MyFile* file)
{
    //刷新实际上是将库缓冲区的内容写到文件内核缓冲区
    if(file->fileno < 0) return;
    write(file->fileno, file->outbuffer, file->bufferlen);
    file->bufferlen = 0;//刷新之后file就没了，已经拷贝了
    //刷新到文件内核缓冲区之后，应该直接再将数据拷贝到磁盘
    fsync(file->fileno);
}
void MyFwrite(const void* ptr, size_t len, MyFile* file)
{
    if(file == NULL) return;
    //写入实际上是拷贝
    memcpy(file->outbuffer + file->bufferlen, ptr, len);
    file->bufferlen += len;
    //写入之后要考虑要不要刷新的问题
    if((file->flush_method & LINE_FLUSH) && file->outbuffer[file->bufferlen-1] == '\n')
    {
        //行刷新
        MyFflush(file);
    }
}
